<?php

namespace app\api\controller\yalimedia;

use addons\shopro\model\UserOauth;
use addons\yalimedia\library\AlibabaCloundHelper;
use app\admin\model\yalimedia\course\Content;
use app\admin\model\yalimedia\course\Contentlog;
use app\admin\model\yalimedia\Order;
use app\common\controller\Api;
use Yansongda\Pay\Exceptions\GatewayException;

/**
 * 课程接口
 */
class Course extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 获取课程列表
     * @throws \think\Exception
     */
    public function index()
    {
        $keyword = $this->request->post('keyword');
        $cid = $this->request->post('cid');
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $where = [];
        if($keyword){
            $where['title'] = ['like','%'.$keyword.'%'];
        }
        if($cid){
            $where['cate_id'] = $cid;
        }
        $subject = new \addons\yalimedia\service\Course();
        $data = $subject->getCourseList($where,$page,$limit);
        foreach($data['data'] as &$v){
            $v['cover'] = $this->request->domain().$v['cover'];
        }
        $this->success('请求成功', $data);
    }

    /**
     * 获取热门课程列表
     * @throws \think\Exception
     */
    public function hot()
    {
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $subject = new \addons\yalimedia\service\Course();
        $data = $subject->getHotCourseList($page,$limit);
        foreach($data['data'] as &$v){
            $v['cover'] = $this->request->domain().$v['cover'];
        }
        $this->success('请求成功', $data);
    }


    /*
     * 课程详情
     */
    public function info(){
        $id = $this->request->post('id');

        $course = new \addons\yalimedia\service\Course();
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->error($course->error);
        }
        $this->success('请求成功', $courseInfo);
    }

    /**
     * 收藏/取消收藏课程
     */
    public function fav(){
        $id = $this->request->post('id');
        $fav = new \addons\yalimedia\service\Fav();
        $return = $fav->act(1,$id,$this->auth->id);

        $this->success('请求成功',$return);
    }

    /**
     * 获取分类
     */
    public function categories(){
        $model = new \app\admin\model\yalimedia\course\Category();
        $categorylist = collection($model->field("id,name")->where(['pid'=>0,'status'=>'normal'])->order("weigh asc,id asc")->select())->toArray();
        foreach($categorylist as &$v){
            $model = new \app\admin\model\yalimedia\course\Category();
            $childlist = collection($model->field("id,name")->where(['pid'=>$v['id'],'status'=>'normal'])->order("weigh asc,id asc")->select())->toArray();
            $v['child'] = $childlist;
        }
        $this->success('请求成功',$categorylist);
    }

    /**
     * 获取内容
     */
    public function content(){
        $content_id = $this->request->post("id");
        $courseContentModel = new Content();
        if(!$content = $courseContentModel->where(['id'=>$content_id])->find()){
            $this->error("当前内容不存在");
        }

        $courseModel = new \app\admin\model\yalimedia\Course();
        if(!$courseInfo = $courseModel->where(['status'=>1,'id'=>$content['course_id']])->find()){
            $this->error("当前课程不存在");
        }

        //获取用户是否是vip
        $isVip = \addons\yalimedia\service\User::isVip($this->auth->id);

        if(($isVip && $courseInfo['vip_price']>0 ) || (!$isVip && $courseInfo['price']>0)){
            /**
             * 是否购买
             */
            $order = new \app\admin\model\yalimedia\Order();
            if(!$order->where(['type'=>1,'status'=>2,'item_id'=>$courseInfo['id'],'user_id'=>$this->auth->id])->find()){
                $this->error("您还未购买当前课程");
            }
        }


        //记录学习记录
        $contentLogModel = new Contentlog();
        if($contentLog = $contentLogModel->where(['content_id'=>$content['id'],'user_id'=>$this->auth->id])->find()){
            $contentLog->save(['last_time'=>time()]);
        }else{
            $contentLogModel->save([
                'course_id'=>$content['course_id'],
                'user_id'=>$this->auth->id,
                'content_id'=>$content['id'],
                'begin_time'=>time(),
                'last_time'=>time(),
            ]);
        }

        switch ($content['type']){
            case "1":
            case "3":
                $result = $result = AlibabaCloundHelper::instance()->GetPlayInfo($content['media_id']);

                if($result){
                    $data['PlayURL'] =$result['PlayInfoList']['PlayInfo'][0]['PlayURL'] ;
                    $this->success("请求成功",$data);
                }else{
                    $this->error("请求失败");
                }
                break;
            case "2":
                $this->success("请求成功",$content['content']);
                break;
        }
    }

    /**
     * 购买课程
     */
    public function buy(){
        $id = $this->request->post('id');
        $course = new \addons\yalimedia\service\Course();
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->error($course->error);
        }
        $course = new \addons\yalimedia\service\Tool();
        $order_no = $course->create_sn();

        $orderModel = new Order();
        if($orderModel->save([
            'order_no'=>$order_no,
            'user_id'=>$this->auth->id,
            'type'=>1,
            'item_id'=>$id,
            'price'=>\addons\yalimedia\service\User::isVip($this->auth->id)?$courseInfo['vip_price']:$courseInfo['price']
        ])){
            try {
//                $wechatUser = \app\admin\model\yalimedia\Wechat::get(['user_id' => $this->auth->id,'type' =>'mp']);
                $openid = UserOauth::where([
                    'user_id'  => $this->auth->id,
                    'provider' => 'Wechat',
                    'platform' => 'wxMiniProgram'
                ])->value('openid');
                if (!$openid) {
                    $this->error('error openid');
                }
                $params = [
                    'amount'=>\addons\yalimedia\service\User::isVip($this->auth->id)?$courseInfo['vip_price']:$courseInfo['price'],
                    'orderid'=>$order_no,
                    'type'=>"wechat",
                    'title'=>$courseInfo['title'],
                    'notifyurl'=>$this->request->domain()."/api/yalimedia/block/notifyx",
                    'returnurl'=>"",
                    'method'=>"miniapp",
                    'openid'=>$openid,
                ];
                $info = get_addon_info('epay');
                if(empty($info)){
                    $this->error('请到后台插件管理安装《微信支付宝整合》插件');
                }
                $result = \addons\epay\library\Service::submitOrder($params);
            }catch (GatewayException $e){
                $this->error($e->getMessage());
            }

            $this->success('请求成功',$result);
        }else{
            $this->success('请求失败，请稍后再试');
        }
    }

}
